package com.lwlean.test.controller;

import com.lwlean.test.domain.TestData;
import com.lwlean.test.exception.ErrorEnum;
import com.lwlean.test.exception.TestException;
import com.lwlean.test.service.TestDataService;
import com.lwlean.test.utils.RestTemplateUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


@RestController
@RequestMapping(value = "/test")
public class MyRestController {

    final private static Logger log = LoggerFactory.getLogger(MyRestController.class);

    //    @Autowired
//    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TestDataService testDataService;


    /**
     * 获取用户信息
     *
     * @param user
     * @return
     */
//    @RequestMapping(value = "/getUser", method = RequestMethod.POST)
//    public Object getUser(@RequestBody Users user) {
//        log.info("receive message is {}:" + user.toString());
//        final Integer id = user.getId();
//        if (id == null || !NumberUtil.isNumber(id)) {
//            return "userid is not a number";
//        }
//        return userService.getUser(Long.valueOf(id));
//    }

    /**
     * 测试
     *
     * @param name
     * @return
     */
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    public Object getUsers(@RequestParam("name") String name) {
        ExecutorService executor = Executors.newFixedThreadPool(10000);

        for (int i = 0; i < 90000; i++) {
            final int fianl = i;
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    log.info("the i is :{}", fianl);
                }
            });
        }
        return null;

    }

    /**
     * 根据传入的信息增加用户
     *
     * @param user
     * @param result
     * @return
     */
//    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
//    public Object addUser(@Valid @RequestBody Users user, BindingResult result) {
//        log.info("receive message is : {}", user);
//        final String valid = ValidUtil.valid(result);
//        if (StringUtils.isNotBlank(valid)) {
//            throw new TestException(ErrorEnum.PARAMETERS_ERROR.getCode(), valid);
//        }
//        userService.addUser(user);
//        return user;
//    }

    /**
     * 根据id 删除用户 之后改成sid
     *
     * @param id
     * @return
     */
//    @RequestMapping(value = "/delUser", method = RequestMethod.DELETE)
//    public Object delUser(@RequestBody Long id) {
//        log.info("receive delete id is : {}", id);
//        if (id == null || !NumberUtil.isNumber(id)) {
//            return "id is not a number";
//        }
//        userService.dropUser(id);
//        return "drop user success!";
//    }

    /**
     * 测试redis方法
     */
    @RequestMapping(value = "/testRedis", method = RequestMethod.GET)
    public Object testRedis() {
        log.info("into testRedis method");
//        redisTemplate.opsForValue().set("testKey", "testValue");
//        String value = redisTemplate.opsForValue().get("testKey");
//        final boolean contains = redisTemplate.opsForSet().members("finish0701").contains("71672");
//        final String testValue = redisTemplate.opsForValue().get("testKey").toString();
        final String key = "DWG:register:db01-6901-0700-0051";
        final ZSetOperations<String, String> zset = redisTemplate.opsForZSet();
        zset.removeRange(key, 0, 2);
        zset.add(key, "success", 0);
        zset.add(key, "failure", 1);
        zset.add(key, "success", 2);
        zset.add(key, "success", 3);
        log.info("end testRedis method,the value is : {}");
//        log.info("delete key:{}",key);
        zset.range(key, 0, 5).forEach(str -> {
            log.info("zset result:{}",str);
        });
        return "success";
    }

    /**
     * 增加数据一条测试数据
     *
     * @param testData
     * @return
     */
    @RequestMapping(value = "/testData", method = RequestMethod.POST)
    public Object testData(@RequestBody TestData testData) {
        log.info("receive message data is:{}", testData);
        int i = testDataService.insertData(testData);
        log.info("result numbers is :{}", i);
        return i;
    }

    /**
     * 根据插入forNum数量的测试数据
     *
     * @param threadNum
     * @param forNum
     * @return
     */
    @RequestMapping(value = "/testBatchData/{threadNum}/{forNum}", method = RequestMethod.GET)
    public Object testBatchData(@PathVariable(value = "threadNum") int threadNum, @PathVariable(value = "forNum") int forNum) {
        testDataService.insertBatchData(threadNum, forNum);
        return "success";
    }

    /**
     * 测试生产程序接受数据
     *
     * @param formEntity
     */
    @RequestMapping(value = "/testRestUrl", method = RequestMethod.POST)
    public void index(HttpEntity<String> formEntity) {
        log.info("get result: {}", formEntity.getBody().toString());
    }


    /**
     * 接受呼叫信息内容
     * @param formEntity
     */
    @RequestMapping(value = "/receiveFallCall", method = RequestMethod.POST)
    public void receiveFallCall(HttpEntity<String> formEntity) {
        log.info("get fall call result: {}", formEntity.getBody().toString());
    }

    /**
     * 接受电话拨打事件
     * @param formEntity
     */
    @RequestMapping(value = "/receiveEvents", method = RequestMethod.POST)
    public void receiveEvents(HttpEntity<String> formEntity) {
        log.info("get Events result: {}", formEntity.getBody().toString());
    }


    /**
     * get post delete put方式调用接口，并返回结果
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/testRestTemplate", method = RequestMethod.POST)
    public String testRestTemplate(@RequestBody Map<String, Object> map) {
        log.info("get model:{}", map);
        final Object url = map.get("url");
        final Object parameter = map.get("parameter");
        final Object method = map.get("method");

        if (null == url || "".equals(url)) {
            throw new TestException(ErrorEnum.PARAMETERS_ERROR.getCode(), "url不能为空！");
        }
        if (!"get".equals(method) && (null == parameter || "".equals(parameter))) {
            throw new TestException(ErrorEnum.PARAMETERS_ERROR.getCode(), "parameter不能为空！");
        }
        final String result = RestTemplateUtil.setRestTemplate(url.toString(), parameter.toString(), method.toString());
        if (StringUtils.isNotBlank(result)) {
            return result;
        }
        throw new TestException(ErrorEnum.RESTTEMPLATE_ERROR.getCode(), ErrorEnum.RESTTEMPLATE_ERROR.getMessage());
    }

//    @RequestMapping(value = "/testTran", method = RequestMethod.GET)
//    public String testTran() {
//        Users users = new Users();
//        users.setId(1);
//        users.setPhone("222");
//        userService.updateAndGetUser(users);
//        return null;
//    }
}
